import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { ApiService } from '../../../core/api.service';
import { DatePipe } from '@angular/common';

@Component({
    selector: 'app-outstock',
    templateUrl: './outstock.component.html',
    styleUrls: ['./outstock.component.less']
})

export class OutstockComponent implements OnInit {
    step1 = true;
    step2 = false;
    postButton = true;
    allTotal: any = '';
    checkedNumber = 0;
    operating = false;
    operaIndex = 0;
    allChecked = false;
    indeterminate = false;
    disabledButton = true;
    dataSet: any = [];
    displayData = [];
    dataSet2: any = [];
    isVisible = false;
    isOkLoading = false;
    treeTitle = '';
    treeKey = '';
    treeTemp: any = [];
    selectedValue = '';
    treeNode: any = [];
    defaultCheckedKeys = [];
    outTimePost: any = null;
    outTimeString: any = '';
    useManPost: any = '';
    outTypePost: any = '';
    ifMaterial = true;
    ifFormatNum = true;
    ifOutTimePost = true;
    ifUseManPost = true;
    ifOutTypePost = true;
    ifPostButton = true;

    constructor(
        private apiService: ApiService,
        private message: NzMessageService,
        private datePipe: DatePipe
    ) { }

    ngOnInit() {
        this.getList('0', '');
    }
    getList(sqorpz, status) {
        this.apiService.getAllMaterial(sqorpz, status).subscribe((res: any) => {
            if (res.type === 'success') {
                if (!res.data.pageList.length) {
                    this.dataSet = [];
                } else {
                    this.dataSet = res.data.pageList;
                    for (const item of this.dataSet) {
                        item.num = item.RN;
                        item.sdate = !item.DT_SYSDATE ? '' : this.datePipe.transform(item.DT_SYSDATE, 'yyyy-MM-dd HH:mm:ss');
                        item.total = '￥' + item.N_TOTAL$PRICE;
                        item.status = item.VC_STATUS;
                        item.name = item.VC_APPROVER;
                        item.outime = item.DT_OUT$TIME;
                        item.useman = item.VC_USE$MAN;
                        item.class = item.VC_TYPE;
                        item.outid = item.VC_OUT$ID;
                        item.edate = !item.DT_APPR$TIME ? '' : this.datePipe.transform(item.DT_APPR$TIME, 'yyyy-MM-dd HH:mm:ss');
                        if (item.VC_STATUS == 0 || item.VC_STATUS == 3) {
                            item.disabled = false;
                        }
                        if (item.VC_STATUS == 1 || item.VC_STATUS == 2) {
                            item.disabled = true;
                        }
                    }
                }
            }
        });
    }
    selectChange(e) {
        this.getList('0', e);
    }
    backPage1() {
        this.step1 = true;
        this.step2 = false;
    }
    // 申请
    app() {
        this.step1 = false;
        this.step2 = true;
        this.ifMaterial = true;
        this.ifFormatNum = true;
        this.ifOutTimePost = true;
        this.ifUseManPost = true;
        this.ifOutTypePost = true;
        this.ifPostButton = true;
        this.clearData();
    }
    // 提交
    pos() {
        let ids = '';
        for (const item of this.displayData) {
            if (item.checked) {
                ids += ',' + item.VC_OUT$ID;
            }
        }
        if (ids == '') {
            this.message.create('warning', '请选择一条数据进行操作');
            return false;
        }
        this.apiService.getspmaterial(ids.replace(',', ''), '1').subscribe((res: any) => {
            if (res.type === 'success') {
                this.message.create('success', '提交成功');
                this.getList('0', '');
            } else {
                this.message.create('warning', '提交失败');
            }
        });
    }
    // 修改/查看
    opera(index, type) {
        this.operaIndex = index;
        this.step1 = false;
        this.step2 = true;
        this.clearData();

        if (type == 'view') {
            this.ifMaterial = false;
            this.ifFormatNum = false;
            this.ifOutTimePost = false;
            this.ifUseManPost = false;
            this.ifOutTypePost = false;
            this.ifPostButton = false;
            this.outTimeString = this.datePipe.transform(this.dataSet[index].outime, 'yyyy-MM-dd');
        } else {
            this.outTimePost = this.datePipe.transform(this.dataSet[index].outime, 'yyyy-MM-dd');
            this.outTimeString = new Date(this.outTimePost).valueOf();
        }
        this.useManPost = this.dataSet[index].useman;
        this.outTypePost = this.dataSet[index].class;

        this.apiService.getOutitem(this.dataSet[index].outid).subscribe((res: any) => {
            if (res.type === 'success') {
                if (!res.data.pageList.length) {
                    this.dataSet2 = [];
                } else {
                    this.dataSet2 = res.data.pageList;
                    this.dataSet2.forEach((item, dataIndex) => {
                        item.id = item.VC_MATERIAL$ID;
                        item.num = Number(dataIndex) + 1;
                        item.house = item.HOUSENAME;
                        item.batch = item.VC_IN$ID;
                        item.price = item.N_PRICE;
                        item.type = item.MANAME;
                        item.class = item.VC_TYPE;
                        item.time = this.datePipe.transform(item.DT_SYS$DATE, 'yyyy-MM-dd HH:mm:ss');
                        item.numk = item.N_NUMBER;
                        item.numl = item.VC_NUMBER;
                        item.total = 0;
                        this.formatNum(dataIndex);
                        this.defaultCheckedKeys.push(item.id);
                        this.treeTitle += ',' + item.type;
                    })
                    this.treeTitle = this.treeTitle.replace(',', '');
                    this.checkData();
                    if (this.treeKey) {
                        this.defaultCheckedKeys = this.treeKey.split(',');
                    }
                }
            }
        });
    }
    // 打开物资分类弹出层
    material() {
        this.isVisible = true;
        this.apiService.getProbdict('7329de822549448abddc753937d56f7f').subscribe((res: any) => {
            const node = [];
            this.treeNode = res;
            if (res) {
                for (const i in res) {
                    node.push({
                        title: res[i].text,
                        key: res[i].id,
                        checked: false,
                        children: []
                    });
                    if (res[i].children) {
                        // 二级
                        for (const j in res[i].children) {
                            node[i].children.push({
                                title: res[i].children[j].text,
                                key: res[i].children[j].id,
                                checked: false,
                                children: []
                            });
                            if (res[i].children[j].children) {
                                // 三级
                                for (const k in res[i].children[j].children) {
                                    node[i].children[j].children.push({
                                        title: res[i].children[j].children[k].text,
                                        key: res[i].children[j].children[k].id,
                                        checked: false,
                                        isLeaf: true
                                    });
                                }
                            } else {
                                node[i].children.push({
                                    title: res[i].children[j].text,
                                    key: res[i].children[j].id,
                                    checked: false,
                                    isLeaf: true
                                });
                            }
                        }
                    } else {
                        node.push({
                            title: res[i].text,
                            key: res[i].id,
                            checked: false,
                            isLeaf: true
                        });
                    }
                }
            }
            this.treeNode = node;
        });
    }
    handleOk(): void {
        this.isOkLoading = true;
        this.treeTitle = '';
        this.treeKey = '';
        this.defaultCheckedKeys = [];
        for (const item of this.treeTemp) {
            this.treeTitle += ',' + item.title;
            this.treeKey += ',' + item.key;
            this.defaultCheckedKeys.push(item.key);
        }
        this.treeTitle = this.treeTitle.replace(',', '');
        this.treeKey = this.treeKey.replace(',', '');
        this.isVisible = false;
        this.isOkLoading = false;
        if (this.treeKey == '') {
            this.dataSet2 = [];
            this.checkData();
        } else {
            this.getAllMaterial();
        }
    }
    handleCancel(): void {
        this.isVisible = false;
    }
    checkData() {
        if (!this.dataSet2.length) {
            this.postButton = true;
        } else {
            this.postButton = false;
        }
    }
    getAllMaterial() {
        this.apiService.getMatType(this.treeKey).subscribe((res: any) => {
            if (res.type === 'success') {
                if (!res.data.pageList.length) {
                    this.dataSet2 = [];
                } else {
                    this.dataSet2 = res.data.pageList;
                    for (const item of this.dataSet2) {
                        item.id = item.VC_MATERIAL$ID;
                        item.num = item.RN;
                        item.house = item.HOUSENAME;
                        item.batch = item.VC_IN$ID;
                        item.price = item.N_PRICE;
                        item.type = item.MANAME;
                        item.class = item.VC_TYPE;
                        item.time = this.datePipe.transform(item.DT_SYS$DATE, 'yyyy-MM-dd HH:mm:ss');
                        item.numk = item.N_NUMBER;
                        item.numl = 0;
                        item.total = 0;
                    }
                }
                this.checkData();
            }
        });
    }
    formatNum(index) {
        setTimeout(() => {
            let allnumber = 0;
            this.dataSet2[index].total = Number(this.dataSet2[index].price) * Number(this.dataSet2[index].numl);
            for (const item of this.dataSet2) {
                allnumber = allnumber + Number(item.price) * Number(item.numl);
            }
            this.allTotal = '总计 ￥' + allnumber;
        }, 200);
    }
    datepickerChange(e) {
        this.outTimeString = new Date(e).valueOf();
    }
    // 树选择
    nzEvent(event): void {
        this.treeTemp = event.nodes;
        const temp: any = [];

        for (const item of this.treeTemp) {
            if (!item.children.length && item.isChecked) {
                temp.push({
                    key: item.key,
                    title: item.title
                });
            } else {
                for (const list of item.children) {
                    if (!list.children.length && list.isChecked) {
                        temp.push({
                            key: list.key,
                            title: list.title
                        });
                    } else {
                        for (const data of list.children) {
                            if (!data.children.length && data.isChecked) {
                                temp.push({
                                    key: data.key,
                                    title: data.title
                                });
                            }
                        }
                    }
                }
            }
        }
        this.treeTemp = temp;
    }
    // 分页
    currentPageDataChange($event: Array<{ name: string; age: number; address: string; checked: boolean, disabled: boolean; }>): void {
        this.displayData = $event;
        this.refreshStatus();
    }

    refreshStatus(): void {
        const allChecked = this.displayData.filter(value => !value.disabled).every(value => value.checked == true);
        const allUnChecked = this.displayData.filter(value => !value.disabled).every(value => !value.checked);
        this.allChecked = allChecked;
        this.indeterminate = (!allChecked) && (!allUnChecked);
    }

    checkAll(value: boolean): void {
        this.displayData.forEach(data => {
            if (!data.disabled) {
                data.checked = value;
            }
        });
        this.refreshStatus();
    }

    operateData(): void {
        this.operating = true;
        setTimeout(() => {
            this.dataSet.forEach(value => value.checked = false);
            this.refreshStatus();
            this.operating = false;
        }, 1000);
    }
    // 清空全部数据
    clearData() {
        this.treeTitle = '';
        this.treeKey = '';
        this.allTotal = '';
        this.outTimeString = '';
        this.useManPost = '';
        this.outTypePost = '';
        this.defaultCheckedKeys = [];
        this.treeNode = [];
        this.dataSet2 = [];
    }
    // 全部提交
    postData() {
        const total = this.allTotal.replace('总计 ￥', '');
        let numl = '';
        let id = '';
        let price = '';
        let batch = '';

        if (!total) {
            this.message.create('warning', '请选择领用数量后再提交');
            return false;
        }
        if (!this.outTimePost) {
            this.message.create('warning', '请选择出库时间');
            return false;
        }
        if (!this.useManPost) {
            this.message.create('warning', '请输入使用人');
            return false;
        }
        if (!this.outTypePost) {
            this.message.create('warning', '请输入出库类型');
            return false;
        }

        for (const item of this.dataSet2) {
            if (item.numl != '0') {
                numl += ',' + item.numl;
                id += ',' + item.id;
                price += ',' + item.price;
                batch += ',' + item.batch;
            }
        }
        this.apiService.getSaveMaterial(
            total,
            this.outTimeString,
            this.useManPost,
            '1',
            this.outTypePost,
            id.replace(',', ''),
            numl.replace(',', ''),
            price.replace(',', ''),
            batch.replace(',', ''),
            (res) => {
                if (res.type === 'success') {
                    this.message.create('success', '提交成功');
                    this.step1 = true;
                    this.step2 = false;
                    this.clearData();
                    this.getList('0', '');
                } else {
                    this.message.create('warning', '提交失败');
                }
            }
        );
    }
}
